<?php

//We'll use this in the search method.    
App::import('Sanitize');

class ApplicationsController extends AppController {

var $name = 'Applications';

//var $uses = array('User', 'Application');

function beforeFilter() {
	parent::beforeFilter();
	if (isset($this->passedArgs[0]) && $this->Auth->user('group_id') == 2) {
  	$aco = $this->Acl->Aco->findByModelAndForeignKey('Application', $this->passedArgs[0]);
    $aro = $this->Acl->Aro->findByModelAndForeignKey('User', $this->Auth->user('id'));
    if (!$this->Acl->check($aro['Aro'], $aco['Aco'])) {
      $this->Session->setFlash($this->Auth->authError, 'flash_failure');
    	$this->redirect($this->referer());
    }
	}
}

///////////////////////////////////////////////////////////////////////////////	
// This view is really reserved for admins and reviewers.
function index() {
		
	$this->Application->recursive = 0;
	$this->set('applications', $this->paginate());
}

///////////////////////////////////////////////////////////////////////////////	

function view($id = null) {
	if (!$id) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	$this->Application->read(null, $id);
	
	//If this has been requested by an element, then return the data.
	if (isset($this->params['requested'])) {
		return $this->Application->data;
	}
	
	$this->set('app', $this->Application->data);
	
	//Set a bunch of content variables.
	if($this->Application->data['Application']['complete'])
		$this->set('applicationViewComplete', $this->_getContentMsg('application_view_complete_txt'));
	
	if($this->Acl->check('Applicants','controllers/Applications/edit'))
		$this->set('welcome', $this->_getContentMsg('application_view_welcome'));
	else
		$this->set('welcome', $this->_getContentMsg('application_view_welcome_noedit'));
		
	$this->set('checklist', $this->_getContentMsg('application_view_checklist'));
}

///////////////////////////////////////////////////////////////////////////////	

function transcripts($id = null) {

	if (!$id) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	$this->Application->read(null, $id);
	$this->set('app', $this->Application->data);
	$this->set('info', $this->_getContentMsg('applications_transcripts_info'));
	
}

///////////////////////////////////////////////////////////////////////////////	

function toefl($id = null) {

	if (!$id) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	$this->Application->read(null, $id);
	$this->set('app', $this->Application->data);
	$this->set('info', $this->_getContentMsg('applications_toefl_info'));
	
}

///////////////////////////////////////////////////////////////////////////////	

function gre($id = null) {

	if (!$id) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	$this->Application->read(null, $id);
	$this->set('app', $this->Application->data);
	$this->set('info', $this->_getContentMsg('applications_gre_info'));
	
}

///////////////////////////////////////////////////////////////////////////////	

function edit($id = null) {
	if (!$id && empty($this->data)) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	if (!empty($this->data)) {
		if ($this->Application->save($this->data)) {
			//We saved so change status.
			$this->Application->change_status($id, 'pif', 2, '');
			$this->Session->setFlash(__('The Application has been updated', true), 'flash_success');
			$this->data = $this->Application->read();
		} else {
			$this->Session->setFlash(
				__('The application could not be saved. Please, try again.', true), 'flash_failure');
		}
	}
	if (empty($this->data)) {
		$this->data = $this->Application->read(null, $id);
	}
	
}

///////////////////////////////////////////////////////////////////////////////

function export() {

	$this->data= $this->Application->find('all');
	$this->render(null, 'file');

}

///////////////////////////////////////////////////////////////////////////////

/**
* Show Report View for applicant
* @param int $id of applicant
*/
function report ($id = null, $type = null) {

	if (!$id) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	$this->data = Sanitize::clean($this->Application->find('first', array('conditions' => array(
																	'Application.id' => $id),
																	'recursive' => 2)));
	
	if($type == "pdf") {
		Configure::write('debug',0);
		$filename = $this->data['Application']['lastname'] . '_' . $this->data['Application']['firstname'];
		$filename .= '_report'; 
		$this->set('filename', $filename);
		$this->render('report_pdf', 'file');
	}
	
}

///////////////////////////////////////////////////////////////////////////////

	/**
	* Modify status messages for applicants
	*/
function modifyStatus ($id = null) {

	if (!$id && empty($this->data)) {
		$this->Session->setFlash(__('Invalid application', true),'flash_failure');
		$this->redirect($this->referer());
	}
	
	if (!empty($this->data)) {
		if($this->Application->save($this->data)) {
			$this->Session->setFlash(__('The Application has been updated', true), 'flash_success');
		} else {
			$this->Session->setFlash(
				__('The application status could not be saved. Please, try again.', true), 'flash_failure');
		}	
	}

	if (empty($this->data))
		$this->data = $this->Application->read(null, $id);
	
	$this->set('app_id', $id); 
	
}

/**
* Email account search.
*/
	function adminSearch() {
		
		
		
		if (empty($this->data)) {
			$this->redirect($this->referer());
		} else {
			$user = $this->Application->find('first', array(
																				'conditions' => array('User.email' => $this->data['email'],
																															'User.group_id' => '2')));
			if(!empty($user)) 
				$this->redirect('/applications/view/'. $user['Application']['id']);
			else {
				$this->Session->setFlash(
					__('Unable to find applicant with that email address.', true), 'flash_failure');
				$this->redirect($this->referer());
			}
		}
	}


///////////////////////////////////////////////////////////////////////////////	

function search() {

	if ((!empty($this->data) && isset($this->data['Search']))
			|| (array_key_exists('page', $this->params['named'])
				&& $this->Session->check('Search')
			   )
	   )
	{
		if(isset($this->data['Search'])) {
			$search = $this->data['Search'];
			$this->_saveSearch($this->data['Search']);
		} else {
			$search = $this->Session->read('Search');
		}

		$criteria = $this->_buildQuery($search);
		$this->set('debug', $criteria);

		$this->paginate = array(
				'conditions' => $criteria,
				'recursive' => 1
				);

		$results = $this->paginate('Application'); 

		if (!count($results)) {
			$this->Session->setFlash('Sorry, no records matched your search criteria.' ,
					'flash_failure', null, 'sr');
		} else {
			$this->set(compact('results'));
		}	
	}

	//Now set some values from the appInfoElements.
	$this->set('grad_area', $this->_parseOptions('studyinterest_grad_area')); 
	$this->set('res_area', $this->_parseOptions('studyinterest_research_area'));
	$this->set('faculty_list', $this->_parseOptions('studyinterest_faculty_list'));

	if ($this->RequestHandler->isAjax()) {
		$this->render('searchresults', 'ajax');
	}

}

///////////////////////////////////////////////////////////////////////////////////////////////
/**
* Internal function for building search queries
* @param array $data search criteria
*/
function _buildQuery($data) {
	$clean = Sanitize::clean($data);

	$criteria = array();
	$or = array();
	$and = array();

	if (!empty($clean['name'])) {
		array_push($or, array( 
					'OR' => array(
						array('Application.lastname LIKE' => "%{$clean['name']}%"),
						array('Application.firstname LIKE' => "%{$clean['name']}%")
						)
				     )
			  ); 
	}

	if (!empty($clean['email'])) {
		array_push($or, array('User.email' => $clean['email']));
	}

	if (!empty($clean['area'])) {
		$val = array( 'OR' => array(
					array('Studyinterest.area_1' => $clean['area']),
					array('Studyinterest.area_2' => $clean['area']),
					array('Studyinterest.area_3' => $clean['area']),
					array('Studyinterest.area_4' => $clean['area'])
					)
			    );
		array_push($and, $val);
	}

	if (!empty($clean['interest'])) {
		$val = array( 'OR' => array(
					array('Studyinterest.res_area_1' => $clean['interest']),
					array('Studyinterest.res_area_2' => $clean['interest']),
					array('Studyinterest.res_area_3' => $clean['interest']),
					array('Studyinterest.res_area_4' => $clean['interest'])
					)
			    );
		array_push($and, $val); 
	}

	if (!empty($clean['faculty'])) {
		$val = array( 'OR' => array(
					array('Studyinterest.faculty_1' => $clean['faculty']),
					array('Studyinterest.faculty_2' => $clean['faculty']),
					array('Studyinterest.faculty_3' => $clean['faculty']),
					array('Studyinterest.faculty_4' => $clean['faculty'])
					)
			    );
		array_push($and, $val);
	}

	if(count($or) == 1) {
		array_push($criteria, $or[0]);
	} elseif(count($or) > 1) {
		$orquery['OR'] = $or;
		array_push($criteria, $orquery);
	}

	if(count($and) == 1) {
		array_push($criteria, $and[0]); 
	} elseif(count($and) > 1) {
		$andquery['AND'] = $and;
		array_push($criteria, $andquery);
	}
	return $criteria;
}

///////////////////////////////////////////////////////////////////////////////////////////////
/**
* Internal function for building search queries
* @param array $data search criteria
*/
function _saveSearch($data) {
	$clean = Sanitize::clean($data);
	$this->Session->delete("Search");
	$this->Session->write("Search.name", $clean['name']);
	$this->Session->write("Search.email", $clean['email']);
	$this->Session->write("Search.area", $clean['area']);
	$this->Session->write("Search.interest", $clean['interest']);
	$this->Session->write("Search.faculty", $clean['faculty']);
}


} //end controller.
